﻿using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text;
using System.Web;
using Newtonsoft.Json.Linq;

namespace Noria.Web.Utility
{
    /// <summary>
    /// Summary description for extract
    /// </summary>
    public class ExtractHandler : IHttpHandler
    {
        private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        public void ProcessRequest(HttpContext context)
        {
            if (context.Request.HttpMethod != "POST")
                throw new MethodNotAllowedException();

            var length = context.Request.ContentLength;
            var buffer = context.Request.BinaryRead(length);
            dynamic payload = JObject.Parse(Encoding.UTF8.GetString(buffer));

            var file = Path.Combine(context.Server.MapPath("tmp"), (string)payload.name);
            var path = context.Server.MapPath((string)payload.path);

            NZip.ExtractToDirectory(file, path);
            log.InfoFormat("Extract file {0} [{1}] to {2}", (string)payload.name, new FileInfo(file).Length, path);
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}